<script setup>
import { ref } from 'vue'
import ChannelSelect from '@/views/article/components/ChannelSelect.vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { Plus } from '@element-plus/icons-vue'
import { articleGetDetailService, articlePubService, articleUpdateService } from '@/api/article.js'
import { baseURL } from '@/utils/request.js'
import axios from 'axios'

const visibleDrawer = ref(false)
const imgUrl = ref('')

const defaultModel = ref({
  id: '',
  title: '',
  cate_id: '',
  cover_img: '',
  content: '',
  state: ''
})

const formModel = ref({ ...defaultModel.value })
const editRef = ref()

const onSelectFile = (file) => {
  imgUrl.value = URL.createObjectURL(file.raw)
  formModel.value.cover_img = file.raw
}

/**
 * 改变组件内部数据的接口
 * @param row
 */
const open = async (row) => {
  // 显示抽屉
  visibleDrawer.value = true
  formModel.value.title = row.title
  formModel.value.cate_id = row.cate_id
  formModel.value.state = row.state

  if (row.id) {
    // 需要获取详情数据
    const res = await articleGetDetailService(row.id)
    formModel.value = res.data.data
    // 图片需要拼接
    imgUrl.value = baseURL + res.data.data.cover_img

    // 更新时，后台接口需要的是file对象格式
    formModel.value.cover_img = await urlToFile(imgUrl.value, formModel.value.cover_img)
  } else {
    formModel.value = { ...defaultModel.value }
    imgUrl.value = ''
    editRef.value.setHTML('')
  }
}

/**
 * 将网络图片URL转换为File对象
 * @param {string} imageUrl 图片URL
 * @param {string} filename 文件名
 * @returns {Promise<File>}
 */
async function urlToFile(imageUrl, filename) {
  try {
    // 1. 获取图片数据
    const response = await axios({
      method: 'get',
      url: imageUrl,
      responseType: 'arraybuffer' // 重要：获取二进制数据
    })

    // 2. 将 ArrayBuffer 转换为 Blob
    const blob = new Blob([response.data], { type: response.headers['content-type'] })

    // 3. 将 Blob 转换为 File 对象
    return new File([blob], filename, { type: response.headers['content-type'] })
  } catch (error) {
    console.error('转换图片失败:', error)
    throw error
  }
}

// 向外提供一个可改变内部数据的方法
defineExpose({ open })

const emit = defineEmits(['success'])
/**
 * 发布文章
 * @param state 状态：已发布、草稿
 */
const addArticle = async (state) => {
  formModel.value.state = state
  const formData = new FormData()
  for (let k in formModel.value) {
    formData.append(k, formModel.value[k])
  }
  if (formModel.value.id) {
    await articleUpdateService(formData)
    ElMessage.success('编辑成功')
  } else {
    console.log(formModel.value)
    await articlePubService(formData)
    ElMessage.success('添加成功')
    visibleDrawer.value = false
    // 向外通知
    emit('success')
  }
}
</script>

<template>
  <el-drawer
    v-model="visibleDrawer"
    :title="formModel.id ? '编辑文章' : '添加文章'"
    direction="rtl"
    size="50%"
  >
    <!-- 发表文章表单 -->
    <el-form :model="formModel" ref="formRef" label-width="100px">
      <el-form-item label="文章标题" prop="title">
        <el-input v-model="formModel.title" placeholder="请输入标题"></el-input>
      </el-form-item>
      <el-form-item label="文章分类" prop="cate_id">
        <channel-select v-model="formModel.cate_id" width="100%"></channel-select>
      </el-form-item>
      <el-form-item label="文章封面" prop="cover_img">
        <!-- 关闭自动上传 -->
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :auto-upload="false"
          :on-change="onSelectFile"
        >
          <img v-if="imgUrl" :src="imgUrl" class="avatar" alt="图片" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="文章内容" prop="content">
        <div class="editor">
          <quill-editor
            ref="editRef"
            v-model:content="formModel.content"
            content-type="html"
            theme="snow"
          ></quill-editor>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button @click="addArticle('已发布')" type="primary">发布</el-button>
        <el-button @click="addArticle('草稿')" type="info">草稿</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>
<style scoped lang="scss">
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
</style>
